package com.eeepay.eeepay_v2.activity;


import android.content.Intent;
import android.text.TextUtils;
import android.view.View;
import android.widget.AbsListView;
import android.widget.AdapterView;
import android.widget.CompoundButton;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.SearchView;
import android.widget.TextView;
import android.widget.ToggleButton;

import com.eeepay.eeepay_v2.R;
import com.eeepay.eeepay_v2.adapter.HistoryAdapter;
import com.eeepay.eeepay_v2.model.UserInfo;
import com.eeepay.eeepay_v2.util.Constant;
import com.eeepay.eeepay_v2.util.GrpcUtils;
import com.eeepay.v2_library.ui.ABBaseActivity;
import com.eeepay.v2_library.view.TitleBar;

import java.util.Arrays;

import cn.eeepay.api.grpc.nano.TerminalApiServiceGrpc;
import cn.eeepay.api.grpc.nano.TerminalSerProto;
import io.grpc.ManagedChannel;

/**
 * Created by Ching on 2016/3/1.
 * 代理商搜索查询
 */
public class AgentQueryActivity extends ABBaseActivity {

    private SearchView searchView;//搜索框
    private ListView lv_content;
    private TitleBar titleBar;
    private LinearLayout tv_includeLower;//包涵下级
    private ToggleButton mToggleButton;
    private HistoryAdapter adapter;//adapter

    private String intentFlag;
    private int currPage = 1;

    private int lastItem;
    private int sum;

    @Override
    protected int getLayoutId() {
        return R.layout.activity_agent_query;
    }

    @Override
    protected void initWidget() {

        if(bundle != null){
            intentFlag = bundle.getString(Constant.INTENT_FLAG);
        }

        titleBar = getViewById(R.id.tb_agent_query);
        tv_includeLower = getViewById(R.id.llayout_include_lower);
        mToggleButton = getViewById(R.id.mTogBtn);

        if(Constant.DEVICE_ISSUE_FLAG.equals(intentFlag)){
            tv_includeLower.setVisibility(View.GONE);
        }

        //搜索提示框
        searchView = getViewById(R.id.actv_search);
        // 设置该SearchView默认是否自动缩小为图标
        searchView.setIconifiedByDefault(false);
        // 设置该SearchView显示搜索按钮
//        searchView.setSubmitButtonEnabled(true);

        lv_content = getViewById(R.id.lv_query_content);
        adapter = new HistoryAdapter(mContext);
        lv_content.setAdapter(adapter);

        sendHttpRequest(0);


    }

    @Override
    protected void eventOnClick() {

        // 为该SearchView组件设置事件监听器
        searchView.setOnQueryTextListener(new SearchView.OnQueryTextListener() {

            // 单击搜索按钮时激发该方法
            @Override
            public boolean onQueryTextSubmit(String query) {
                return false;
            }

            // 用户输入字符时激发该方法
            @Override
            public boolean onQueryTextChange(String newText) {
                if (TextUtils.isEmpty(newText)) {
                    // 清除ListView的过滤
                    adapter.getFilter().filter("");
//                    lv_content.clearTextFilter();
                } else {
                    // 使用用户输入的内容对ListView的列表项进行过滤
//                    lv_content.setFilterText(newText);
                    adapter.getFilter().filter(newText);
                }
                return true;
            }
        });

        lv_content.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                Intent intent = new Intent();
                intent.putExtra("agentName", adapter.list.get(position).agentName);
                intent.putExtra("agentNo", adapter.list.get(position).agentNo);
                intent.putExtra("agentNode", adapter.list.get(position).agentNode);
                setResult(RESULT_OK, intent);
                finish();
            }
        });

        mToggleButton.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
                mToggleButton.setChecked(true);
            }
        });

        lv_content.setOnScrollListener(new AbsListView.OnScrollListener() {
            @Override
            public void onScrollStateChanged(AbsListView view, int scrollState) {
                if (lastItem == adapter.getCount()
                        && scrollState == AbsListView.OnScrollListener.SCROLL_STATE_IDLE) {
                    if(currPage * 20 < sum){
                        currPage++;
                        sendHttpRequest(0);
                    }
                }
            }

            @Override
            public void onScroll(AbsListView view, int firstVisibleItem, int visibleItemCount, int totalItemCount) {
                lastItem = firstVisibleItem + visibleItemCount;
            }
        });

    }

    @Override
    protected void sendHttpRequest(int taskId) {
        showProgressDialog();
        GrpcUtils.getInstance().doGrpcTask(Constant.URL.URL, Constant.URL.PORT
                , taskId, new GrpcUtils.AsyncTaskListener() {
            @Override
            public Object doInBack(ManagedChannel channel, int taskId) {
                TerminalApiServiceGrpc.TerminalApiServiceBlockingStub stub = TerminalApiServiceGrpc.newBlockingStub(channel);
                TerminalSerProto.TerminalRequest request = new TerminalSerProto.TerminalRequest();
                request.loginAgentNo = UserInfo.getUserInfo2SP().getAgentNo();
                request.pageNo = currPage;
                request.pageSize = 20;
                TerminalSerProto.AgentInfoResponse response = stub.chooseAgent(request);
                return response;
            }

            @Override
            public void updateUI(Object result, int taskId) {
                dismissProgressDialog();
                if(result == null){
                    showToast("查询失败");
                    return;
                }
                TerminalSerProto.AgentInfoResponse response = (TerminalSerProto.AgentInfoResponse) result;
                sum = response.total;
                if("false".equals(response.resultTerResponse.status)){
                    showToast(response.resultTerResponse.msg);
                    return;
                }
                TerminalSerProto.AgentInfoMsg[] data = response.agentInfoMsg;
                adapter.addAll(Arrays.asList(data));
            }
        });
    }

}
